package org.oslog.webapp.web.common.filter;

import java.io.IOException;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.oslog.webapp.web.common.utils.WebUtil;

import com.tomaer.platform.framework.sh.security.core.common.utils.LogUtil;
import com.tomaer.platform.framework.sh.security.core.sysmain.model.User;

public class SecurityFilter implements Filter{

	static final LogUtil logger = LogUtil.getLogger(SecurityFilter.class);
	
	private String noPermission;
	private Set<String> exclude;
	
	public void init(FilterConfig arg0) throws ServletException {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		User user = (User)WebUtil.getUser(request);
		Set<String> urlSet = WebUtil.getUrlSet(request);
		String reqUrl = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath());
		if (urlSet != null) {
			if (!exclude.contains(reqUrl)) {
				if (!urlSet.contains(reqUrl)) {
					logger.debug("Rejected "+user.getId()+" 's requested URL: ["+reqUrl+"]");
					request.getRequestDispatcher(noPermission).forward(arg0, arg1);
				}
			}
		}
		arg2.doFilter(arg0, arg1);
	}

	public void destroy() {
		
	}

	public String getNoPermission() {
		return noPermission;
	}

	public Set<String> getExclude() {
		return exclude;
	}

	public void setNoPermission(String noPermission) {
		this.noPermission = noPermission;
	}

	public void setExclude(Set<String> exclude) {
		this.exclude = exclude;
	}
	
}
